package org.dream.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dream.domain.Daydeal;
import org.dream.domain.Dealrecord;
import org.dream.domain.Industry;
import org.dream.domain.Stock;
import org.dream.persistence.PersistenceService;
import org.dream.persistence.PersistenceServiceImpl;
import org.dream.util.DoubleUtil;
import org.dream.util.FileUtil;
import org.dream.util.Log;
import org.dream.util.LogFactory;
import org.dream.util.ReaderExcel;
import org.dream.util.UUID;

/**
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class ImportServiceImpl implements ImportService {
	private PersistenceService persistenceService = new PersistenceServiceImpl();

	public List<Stock> canOrNotImportStocks(String fileName, final List<Stock> _exist_stocks) {
		List<Stock> _import_stocks = new ArrayList<Stock>();
		List<Stock> improtStocks = getImportStocks(fileName);
		// 判断数据库是否存在
		List<String> codes = new ArrayList<String>();
		for (Stock stock : improtStocks) {
			codes.add(stock.getCode());
		}
		List<Stock> exsits = persistenceService.getStocksByCode(codes);
		if (null == exsits || exsits.size() == 0) {
			// 如果数据库不存在
			_import_stocks.addAll(improtStocks);
		} else {
			// 如果数据库存在不可导入的
			_exist_stocks.addAll(exsits);
			// 把数据库中不存在的加入导入
			for (Stock stock : improtStocks) {
				boolean exsitsFlag = false;
				for (Stock exStock : exsits) {
					if (stock.getCode().equals(exStock.getCode())) {
						exsitsFlag = true;
						break;
					}
				}
				if (!exsitsFlag) {
					_import_stocks.add(stock);
				}

			}
		}
		return _import_stocks;

	}

	private List<Stock> getImportStocks(String fileName) {
		List<Stock> stocks = new ArrayList<Stock>();
		File[] files = FileUtil.getFiles(fileName);

		for (File file : files) {
			try {
				String lineString;
				String bkmc = file.getName().split("\\.")[0];
				FileInputStream fileInputStream = null;
				InputStreamReader inputStreamReader = null;
				fileInputStream = new FileInputStream(file);
				inputStreamReader = new InputStreamReader(fileInputStream, "gbk");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				lineString = bufferedReader.readLine();
				lineString = bufferedReader.readLine();
				while (StringUtils.isNotEmpty(lineString)) {
					Stock stock = new Stock();
					stock.setId(UUID.getUUID());
					stock.setCode(lineString.split("\t")[0]);
					stock.setName(lineString.split("\t")[1]);
					stock.setBkmc(bkmc);
					stocks.add(stock);
					lineString = bufferedReader.readLine();

				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return stocks;
	}

	public void importIndustrys(String fileName) {
		List<Industry> industries = new ArrayList<Industry>();
		File[] files = new File(fileName).listFiles();
		for (File file : files) {
			try {
				String lineString;
				FileInputStream fileInputStream = null;
				InputStreamReader inputStreamReader = null;
				fileInputStream = new FileInputStream(file);
				inputStreamReader = new InputStreamReader(fileInputStream, "gbk");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				lineString = bufferedReader.readLine();
				String day = lineString.substring(lineString.length() - 12).split(",")[0].replaceAll("-", "/");
				String week = lineString.substring(lineString.length() - 12).split(",")[1];
				lineString = bufferedReader.readLine();
				lineString = bufferedReader.readLine();
				while (StringUtils.isNotEmpty(lineString)) {
					String[] strs = lineString.replaceAll(" ", "").replaceAll(" ", "").split("\t");
					lineString = bufferedReader.readLine();
					if (strs.length == 1) {
						continue;
					}
					Industry industry = new Industry();
					industry.setId(UUID.getUUID());
					industry.setBkmc(strs[0]);
					industry.setJzf(Double.valueOf(strs[1]));
					industry.setQzf(Double.valueOf(strs[2]));
					industry.setZcj(strs[3]);
					industry.setScb(Double.valueOf(strs[4]));
					industry.setHsl(Double.valueOf(strs[5]));
					industry.setSy_d(Double.valueOf(strs[6]));
					industry.setLzgp(strs[7]);
					industry.setZgb(strs[8]);
					industry.setDay(day);
					industry.setWeek(week);
					industries.add(industry);

				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		persistenceService.saveList(industries);
	}

	/**
	 * 得到文件里的股票数据
	 */
	public List<Daydeal> getDaydealListByFile(File file) throws FileNotFoundException, IOException {
		Stock stockImport = getStockByFile(file);
		Daydeal daydealRecently = persistenceService.findRecentlyDaydeal(stockImport.getCode());
		List<Daydeal> listDaydeal = new ArrayList<Daydeal>();
		FileInputStream fileInputStream = null;
		InputStreamReader inputStreamReader = null;
		fileInputStream = new FileInputStream(file);
		inputStreamReader = new InputStreamReader(fileInputStream, "gbk");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		// 取得股票名称
		String lineString = bufferedReader.readLine();
		String name = lineString.split(" ")[1];
		String code = file.getName().split("\\.")[0];
		// 跳过一行
		lineString = bufferedReader.readLine();
		lineString = bufferedReader.readLine();
		Daydeal preDaydeal = (null == daydealRecently) ? null : daydealRecently;
		int dayNum = (null == daydealRecently) ? 0 : daydealRecently.getDayNum() + 1;
		while (StringUtils.isNotEmpty(lineString)) {

			lineString = lineString.replaceAll(" ", "");
			lineString = lineString.replaceAll("　", "");
			String[] strArray = lineString.split(",");
			// 下一行
			lineString = bufferedReader.readLine();
			// 如果数据库有数据，并且要导入的行小于或等于数据库最小的行则不导入
			if (null != preDaydeal && strArray[0].compareTo(preDaydeal.getDAY()) <= 0) {
				continue;
			}
			Daydeal daydeal = new Daydeal();
			daydeal.setId(UUID.getUUID());// 设置主键
			daydeal.setCode(code);// 设置股票编码
			daydeal.setName(name);// 设置股票名字
			daydeal.setDAY(strArray[0]);// 设置日期
			daydeal.setDayNum(dayNum);
			try {
				daydeal.setOPEN(Double.parseDouble(strArray[1]));// 设置开盘价
				daydeal.setHIGH(Double.parseDouble(strArray[2]));// 设置最高价
				daydeal.setLOW(Double.parseDouble(strArray[3]));// 设置最低价
				daydeal.setCLOSE(Double.parseDouble(strArray[4]));// 设置收盘价
				daydeal.setVOL(Double.parseDouble(strArray[5]));// 设置成交量
				// 计算涨幅
				double zhangFu = 0.0;
				double VOLZhangfu = 0.0;
				if (null != preDaydeal) {
					if (Math.abs(preDaydeal.getCLOSE() - 0) < 0.0001) {
						zhangFu = 0.0;
					} else {
						zhangFu = (daydeal.getCLOSE() - preDaydeal.getCLOSE()) / preDaydeal.getCLOSE()
								* 100;
					}
					// 如果昨天没停盘
					if (Math.abs(preDaydeal.getVOL() - 0) < 0.0001) {
						VOLZhangfu = 0;
					} else {

						VOLZhangfu = (daydeal.getVOL() - preDaydeal.getVOL()) / preDaydeal.getVOL()
								* 100;
					}

					zhangFu = DoubleUtil.changeDecimal(zhangFu, 6);
					VOLZhangfu = DoubleUtil.changeDecimal(VOLZhangfu, 6);

				}
				daydeal.setRiseWidth(zhangFu);
				daydeal.setVOLRiseWidth(VOLZhangfu);
				listDaydeal.add(daydeal);
				dayNum++;
				preDaydeal = daydeal;
			} catch (Exception e) {
				String errStr = daydeal.getCode() + daydeal.getName() + daydeal.getDAY() + "出错";
				e.printStackTrace();
				LogFactory.getLog().logError(errStr);
				throw new RuntimeException(errStr);

			}
		}
		bufferedReader.close();
		return listDaydeal;
	}

	public void importDealrecords(String fileName) {
		List<Dealrecord> dealRecords = new ArrayList<Dealrecord>();
		List<String[]> list = ReaderExcel.readExcelOneSheet(new File(fileName));
		boolean start = false;
		for (String[] strings : list) {
			if (!start) {
				start = true;
				continue;
			}
			Dealrecord dealRecord = new Dealrecord();
			dealRecord.setId(UUID.getUUID());
			dealRecord.setHappenDate(strings[0].replaceAll("-", "/"));
			dealRecord.setHappenTime(strings[1]);
			dealRecord.setBusinessName(strings[2]);
			dealRecord.setStockCode(strings[3]);
			dealRecord.setStockName(strings[4]);
			dealRecord.setDealPrice(Double.parseDouble(strings[5]));
			dealRecord.setDealNum(Integer.parseInt(strings[6]));
			dealRecord.setDealAmount(Double.parseDouble(strings[7]));
			dealRecord.setStockBalance(Double.parseDouble(strings[8]));
			dealRecord.setCommissionCharge(Double.parseDouble(strings[9]));
			dealRecord.setStampTax(Double.parseDouble(strings[10]));
			dealRecord.setTransferCharge(Double.parseDouble(strings[11]));
			dealRecord.setOtherCharge(Double.parseDouble(strings[12]));
			dealRecord.setHappenCharge(Double.parseDouble(strings[13]));
			dealRecord.setFundsBalance(Double.parseDouble(strings[14]));
			dealRecord.setEntrustCode(strings[15]);
			dealRecord.setEntrustPrice(Double.parseDouble(strings[16]));
			dealRecord.setEntrustNum(Integer.parseInt(strings[17]));
			dealRecord.setStockholderCode(strings[18]);
			dealRecord.setFundsAccount(strings[19]);
			dealRecord.setMoneyKind(strings[20]);
			dealRecord.setDealGroup(0);
			dealRecords.add(dealRecord);
		}
		persistenceService.saveDealRecords(dealRecords);
	}

	/**
	 * 得到文件里的股票数据
	 */
	private Stock getStockByFile(File file) throws FileNotFoundException, IOException {
		Stock stock = new Stock();
		FileInputStream fileInputStream = null;
		InputStreamReader inputStreamReader = null;
		fileInputStream = new FileInputStream(file);
		inputStreamReader = new InputStreamReader(fileInputStream, "gbk");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		// 取得股票名称
		String code = file.getName().split("\\.")[0];
		String str = bufferedReader.readLine();
		String name = str.split(" ")[1];
		stock.setCode(code);
		stock.setName(name);
		stock.setId(UUID.getUUID());
		bufferedReader.close();
		return stock;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.dream.marcket.dao.StockImportService#getMapByFileFolder(java.lang
	 * .String)
	 */
	public void importedDaydeals(String filePath) {
		String id = "importedDaydeals()" + UUID.getUUID();
		LogFactory.getLog().startLogTime(id);
		File[] files = FileUtil.getFiles(filePath);
		int i = 0;
		for (File file : files) {
			List<Daydeal> daydealList = null;// 要导入的股票数据

			try {
				Stock stockImport = getStockByFile(file);
				daydealList = getDaydealListByFile(file);
				if (null != daydealList && daydealList.size() > 0) {
					persistenceService.saveDaydeals(daydealList);
					LogFactory.getLog().logProcess(Log.IMPORTE_DDAYDEALS_PROCESS,
							"导入成功" + i + "：" + stockImport.getName() + stockImport.getCode());
				}
			} catch (Exception e) {
				e.printStackTrace();
				LogFactory.getLog().logProcess(Log.IMPORTE_DDAYDEALS_PROCESS, e.getMessage());
				return;
			}
			i++;

		}
		LogFactory.getLog().logProcess(Log.IMPORTE_DDAYDEALS_PROCESS, "导入完成");
		LogFactory.getLog().endLongTime(id);

	}

	public List<Daydeal> getDaydealListByFiles(String filePath) {
		String id = "importedDaydeals()" + UUID.getUUID();
		List<Daydeal> daydeals = new ArrayList<Daydeal>();
		LogFactory.getLog().startLogTime(id);
		File[] files = FileUtil.getFiles(filePath);
		for (File file : files) {
			List<Daydeal> daydealList = null;// 要导入的股票数据

			try {
				daydealList = getDaydealListByFile(file);
				if (null != daydealList && daydealList.size() > 0) {
					daydeals.addAll(daydealList);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		LogFactory.getLog().logProcess(Log.IMPORTE_DDAYDEALS_PROCESS, "导入完成");
		LogFactory.getLog().endLongTime(id);
		return daydeals;

	}

	public List<Industry> getImportedIndustrys(String filePath) {
		return null;
	}

}
